﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyBlog.Model;

namespace MyBlog.WebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class TypeController : ControllerBase
    {
        private readonly ITypeInfoService typeInfoService;

        public TypeController(ITypeInfoService typeInfoService)
        {
            this.typeInfoService = typeInfoService;
        }
        [HttpGet("Types")]
        public async Task<ApiResult> GetTypes()
        {
            var types = await typeInfoService.QueryAsync();
            if (types.Count==0) return ApiResultHelper.Error("没有更多的烈性");
            return ApiResultHelper.Success(types);
        }
        [HttpPost("Create")]
        public async Task<ApiResult> Create(string name)
        {
            //数据验证
            if (string.IsNullOrEmpty(name)) return ApiResultHelper.Error("类型名不能为空");
            TypeInfo type = new() { Name = name };
            bool b=await typeInfoService.CreateAsync(type);
            if (!b) return ApiResultHelper.Error("添加失败");
            return ApiResultHelper.Success(b);
        }
        [HttpPut("Edit")]
        public async Task<ApiResult> Edit(int id,string name)
        {
            var type=await typeInfoService.FindAsync(id);
            if (type == null) return ApiResultHelper.Error("没有找到改文章类型");
            type.Name = name;
            if (!await typeInfoService.EditAsync(type))
                return ApiResultHelper.Error("修改失败");
            return ApiResultHelper.Success(type);
        }
        [HttpDelete("Delete")]
        public async Task<ApiResult> Delete(int id)
        {
            if (!await typeInfoService.DeleteAsync(id))
                return ApiResultHelper.Error("删除失败");
            return ApiResultHelper.Success(true);
        }
    }
}
